<template>
  <div class="booking-container">
    <!-- 头部导航 -->
    <el-page-header @back="goBack" title="返回">
      <template #content>
        <span class="header-title">{{ room.name }} - 预约流程</span>
      </template>
    </el-page-header>

    <!-- 步骤导航 -->
    <el-steps :active="currentStep" align-center>
      <el-step title="选择时间" />
      <el-step title="选择陪玩" />
      <el-step title="确认订单" />
    </el-steps>

    <!-- 步骤内容 -->
    <div class="step-content">
      <!-- 步骤1：选择时间 -->
      <div v-show="currentStep === 1" class="time-selection">
        <div class="schedule-calendar">
          <div
              v-for="day in scheduleData"
              :key="day.scheduleDate"
              class="day-card"
          >
            <div class="day-header">
              <div class="date">{{ formatDate(day.scheduleDate) }}</div>
              <div class="day-status" :class="getDayStatusClass(day)">
                {{ getDayStatusText(day) }}
              </div>
            </div>

            <div class="time-slots">
              <div
                  v-for="slot in day.slots"
                  :key="slot.id"
                  class="time-slot"
                  :class="getSlotClass(slot)"
                  @click="selectTimeSlot(slot)"
              >
                <div class="slot-time">{{ slot.startTime }} - {{ slot.endTime }}</div>
                <div class="slot-status">{{ getStatusText(slot.status) }}</div>
              </div>
            </div>
          </div>
        </div>

        <div class="selected-time" v-if="selectedSlot">
          已选时段：{{ selectedDate }} {{ selectedSlot.startTime }} - {{ selectedSlot.endTime }}
          <div class="selected-time">
            <el-time-picker
                v-model="selectedTime" is-range
                :disabled-hours="disabledHours"
                :disabled-minutes="disabledMinutes"
                :disabled-seconds="disabledSeconds"
                placeholder="Arbitrary time"
                format="HH:mm"
            />
            </div>
            </div>
            <div class="time-duration" v-if="timeDuration">
              共计 {{ timeDuration }} 分钟
            </div>
          </div>
        </div>

      <!-- 步骤2：选择陪玩 -->
    <div v-show="currentStep === 2" class="escort-selection">
        <div class="escort-grid">
          <el-card
              v-for="escort in availableEscorts"
              :key="escort.id"
              class="escort-card"
              :class="{ 'selected-card': isSelected(escort) }"
              @click="toggleSelection(escort)"
          >
            <!-- 左上角选中指示 -->
            <div class="selection-indicator">
              <el-icon v-if="isSelected(escort)" class="check-icon">
                <Select />
              </el-icon>
            </div>
            <div class="card-header">
              <el-avatar :src="escort.imgUrl" :size="80" />
              <div class="base-info">
                <h3 class="username">{{ escort.username }}</h3>
                <div class="meta">
                  <span class="gender" >
                    <el-icon :style="genderColor(escort.gender)">
                      <component :is="escort.gender === '1' ? 'Male' : 'Female'" />
                    </el-icon>
                    {{ genderText(escort.gender) }} | {{ escort.age }}岁
                  </span>
                  <el-rate
                      v-model="escort.avgRating"
                      disabled
                      :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
                      class="rating"
                  />
                </div>
              </div>
            </div>

            <!-- 图片轮播 -->
            <el-carousel
                v-if="escort.imgUrlList?.length"
                :interval="4000"
                height="200px"
                class="image-carousel"
            >
              <el-carousel-item v-for="(img, index) in escort.imgUrlList" :key="index">
                <el-image
                    :src="img"
                    fit="cover"
                    class="carousel-image"
                    :preview-src-list="escort.imgUrlList"
                />
              </el-carousel-item>
            </el-carousel>

            <!-- 标签显示部分 -->
            <div class="tags">
              <el-tag
                  v-for="tag in matchedTags(escort.tagIdList)"
                  :key="tag.id"
                  type="info"
                  class="tag-item"
              >
                {{ tag.label }}
              </el-tag>
            </div>

            <!-- 详细信息 -->
            <!-- 数据指标区域 -->
            <div class="metrics-grid">
              <div class="metric-item">
                <el-icon class="metric-icon" :style="{color: '#F56C6C'}">
                  <Star />
                </el-icon>
                <div class="metric-content">
                  <div class="metric-value">{{ escort.likes | formatNumber }}</div>
                  <div class="metric-label">点赞</div>
                </div>
              </div>

              <div class="metric-item">
                <el-icon class="metric-icon" :style="{color: '#67C23A'}">
                  <ShoppingCart />
                </el-icon>
                <div class="metric-content">
                  <div class="metric-value">{{ escort.orderNum | formatNumber }}</div>
                  <div class="metric-label">月订单</div>
                </div>
              </div>

              <div class="metric-item">
                <el-icon class="metric-icon" :style="{color: '#409EFF'}">
                  <User />
                </el-icon>
                <div class="metric-content">
                  <div class="metric-value">{{ escort.fansNum | formatNumber }}</div>
                  <div class="metric-label">粉丝</div>
                </div>
              </div>

              <div class="metric-item">
                <el-icon class="metric-icon" :style="{color: '#E6A23C'}">
                  <Connection />
                </el-icon>
                <div class="metric-content">
                  <div class="metric-value">{{ escort.followingNum | formatNumber }}</div>
                  <div class="metric-label">关注</div>
                </div>
              </div>

              <div class="metric-item price-item">
                <el-icon class="metric-icon" :style="{color: '#F56C6C'}">
                  <Coin />
                </el-icon>
                <div class="metric-content">
                  <div class="metric-value">¥{{ escort.price }}/h</div>
                  <div class="metric-label">单价</div>
                </div>
              </div>
            </div>

            <!-- 签名 -->
            <div class="signature">
              <el-text type="info" truncated>{{ escort.signature }}</el-text>
            </div>
          </el-card>
        </div>
      </div>

    <!-- 步骤3：确认订单 -->
    <div v-show="currentStep === 3" class="order-confirm">
      <el-descriptions title="订单详情" :column="1" border>
        <!-- 房间信息 -->
        <el-descriptions-item label="房间名称">{{ room.name }}</el-descriptions-item>
        <el-descriptions-item label="房间描述">{{ room.description || '暂无描述' }}</el-descriptions-item>
        <el-descriptions-item label="人数限制">{{ room.size }}人</el-descriptions-item>

        <!-- 预约时间 -->
        <el-descriptions-item label="预约时间" v-if="selectedSlot">
          {{ selectedDate }} {{ formattedSelectedTime }}
        </el-descriptions-item>

        <!-- 选择陪玩 -->
        <el-descriptions-item label="选择陪玩">
          <div class="escort-list">
            <div v-for="escort in selectedEscorts" :key="escort.id" class="escort-item">
              <el-avatar :src="escort.imgUrl" :size="40" />
              <span class="escort-name">{{ escort.username }}</span>
            </div>
            <span v-if="selectedEscorts.length === 0">未选择陪玩</span>
          </div>
        </el-descriptions-item>

        <!-- 总金额 -->
        <el-descriptions-item label="总金额" class="total-price">
          ¥{{ calculatedPrice.toFixed(2) }}
        </el-descriptions-item>
      </el-descriptions>
    </div>
     <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button
          v-if="currentStep > 1"
          @click="currentStep--"
      >
        上一步
      </el-button>

      <el-button
          type="primary"
          :loading="submitting"
          @click="handleNextStep"
      >
        {{ currentStep === 3 ? '提交订单' : '下一步' }}
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from 'axios'
import dayjs from 'dayjs'
import { ElMessage } from "element-plus";
import {
  Star,
  ShoppingCart,
  User,
  Connection,
  Coin,
  Select
} from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()

const user = ref(getUser());

// 房间信息
const room = ref({
  id: Number(route.params.roomId),
  name: '',
  price: 0,
  shopId: 0
})

// 预约流程状态
const currentStep = ref(1)
const scheduleData = ref([])
const selectedSlot = ref(null)
const availableEscorts = ref([])
const selectedEscorts = ref([])
const submitting = ref(false)
const selectedTime = ref([new Date(), new Date()])

const makeRange = (start, end) => {
  const result= []
  for (let i = start; i <= end; i++) {
    result.push(i)
  }
  return result
}
const disabledHours = () => {
  return makeRange(0, parseInt(selectedSlot.value.startTime.split(":")[0]) - 1)
      .concat(makeRange(parseInt(selectedSlot.value.endTime.split(":")[0]) + 1, 23))
}
const disabledMinutes = (hour) => {
  let startTime = selectedSlot.value.startTime
  let endTime = selectedSlot.value.endTime
  let range = [];
  if (hour === parseInt(startTime.split(":")[0])) {
    range = range.concat(makeRange(0, parseInt(startTime.split(':')[1]) - 1))
  }
  if (hour === parseInt(endTime.split(':')[0])) {
    range = range.concat(makeRange(parseInt(endTime.split(':')[1]) + 1, 59))
  }
  console.log(range)
  return range;
}
const disabledSeconds = (hour, minute) => {
  if (hour === 18 && minute === 30) {
    return makeRange(1, 59)
  }
}
// 计算持续时间
const timeDuration = computed(() => {
  if (!selectedTime.value) return 0
  let startH = selectedTime.value[0].getHours()
  let startM = selectedTime.value[0].getMinutes()
  let endH = selectedTime.value[1].getHours()
  let endM = selectedTime.value[1].getMinutes()
  return (endH - startH) * 60 + (endM - startM)
})

const selectedDate = computed(() => {
  return selectedSlot.value ? formatDate(selectedSlot.value.scheduleDate) : ''
})

// 初始化加载
onMounted(async () => {
  await loadRoomInfo()
  await loadSchedules()
})

// 加载房间基本信息
const loadRoomInfo = async () => {
  try {
    const res = await axios.get(BASE_URL + `/v1/show/room/select?id=`+ room.value.id)
    if (res.data.code === 2000) {
      room.value = res.data.data[0]
    }
  } catch (error) {
    console.error('加载房间信息失败', error)
  }
}

// 加载排班数据
const loadSchedules = async () => {
  try {
    const params = {
      roomId: room.value.id,
      startDate: dayjs().format('YYYY-MM-DD'),
      endDate: dayjs().add(6, 'day').format('YYYY-MM-DD')
    }

    const res = await axios.get(BASE_URL + '/v1/schedule/room/select', { params })
    if (res.data.code === 2000) {
      scheduleData.value = processScheduleData(res.data.data)
    }
  } catch (error) {
    console.error('加载排班失败', error)
  }
}

// 处理排班数据结构
const processScheduleData = (data) => {
  const dateMap = new Map()

  // 生成7天框架
  for (let i = 0; i < 7; i++) {
    const date = dayjs().add(i, 'day').format('YYYY-MM-DD')
    dateMap.set(date, {
      scheduleDate: date,
      slots: [],
      status: '0' // 默认不可用
    })
  }

  // 填充实际数据
  data.forEach(item => {
    const date = dayjs(item.scheduleDate).format('YYYY-MM-DD')
    if (dateMap.has(date)) {
      const slot = {
        ...item,
        startTime: item.startTime.substring(0, 5),
        endTime: item.endTime.substring(0, 5)
      }
      dateMap.get(date).slots.push(slot)

      // 更新当天状态（如果有可预约时段）
      if (slot.status === '1') {
        dateMap.get(date).status = '1'
      }
    }
  })

  return Array.from(dateMap.values())
}

// 选择时间段
const selectTimeSlot = (slot) => {
  if (slot.status !== '1') return
  selectedSlot.value = slot
}



// 步骤处理
const handleNextStep = async () => {
  if (currentStep.value === 1) {
    if (!selectedSlot.value) {
      ElMessage.warning('请选择预约时段')
      return
    }
    await loadEscorts()
    currentStep.value++
  } else if (currentStep.value === 2) {
    currentStep.value++
  } else {
    await submitOrder()
  }
}


// 工具方法
const formatDate = (date) => dayjs(date).format('YYYY-MM-DD ddd')
const getStatusText = (status) => ({
  '0': '不可用',
  '1': '可预约',
  '2': '已预约',
  '3': '使用中'
})[status]

const getSlotClass = (slot) => ({
  'available': slot.status === '1',
  'disabled': slot.status !== '1',
  'selected': selectedSlot.value?.id === slot.id
})

const getDayStatusClass = (day) => ({
  'available': day.status === '1',
  'unavailable': day.status === '0'
})

const getDayStatusText = (day) => day.status === '1' ? '可预约' : '不可约'

// 返回上一页
const goBack = () => {
  router.go(-1)
}


// 新增计算属性格式化时间
const formattedSelectedTime = computed(() => {
  if (!selectedTime.value || selectedTime.value.length !== 2) return '';
  return `${dayjs(selectedTime.value[0]).format('HH:mm')} - ${dayjs(selectedTime.value[1]).format('HH:mm')}`;
});

// 修改后的loadEscorts方法
const loadEscorts = async () => {
  try {
    // 获取用户选择的时间参数
    const scheduleDate = selectedSlot.value.scheduleDate;
    const startTime = dayjs(selectedTime.value[0]).format('HH:mm');
    const endTime = dayjs(selectedTime.value[1]).format('HH:mm');

    // 第一步：获取空闲陪玩排班
    const scheduleParams = {
      scheduleDate,
      startTime,
      endTime,
      status: '1'
    };
    const scheduleRes = await axios.get(BASE_URL+'/v1/schedule/escort/select', { params: scheduleParams });

    // 第二步：获取店家所有陪玩
    const escortParams = { shopId: room.value.shopId };
    const escortRes = await axios.get(BASE_URL+'/v1/show/escort/select', { params: escortParams });

    // 筛选匹配的陪玩
    const availableEscortIds = new Set(scheduleRes.data.data.map(s => s.escortId));
    availableEscorts.value = escortRes.data.data.filter(e =>
        availableEscortIds.has(e.id)
    );
  } catch (error) {
    ElMessage.error('加载陪玩失败');
  }
};


// 标签列表请求
const tagList = ref([])

const loadTags = async () => {
  try {
    // 请求参数根据实际需求调整
    const params = {
      type: '1' // 限制为陪玩相关标签
    }

    const res = await axios.get(BASE_URL+'/v1/show/tag/select', { params })
    if (res.data.code === 2000) {
      tagList.value = res.data.data
    }
  } catch (error) {
    ElMessage.error('标签加载失败')
    console.error('标签加载错误:', error)
  }
}

// 简单ID匹配逻辑
const matchedTags = (tagIds) => {
  if (!tagIds || !tagList.value.length) return []
  return tagList.value.filter(tag =>
      tagIds.includes(tag.id)
  )
}

// 性别显示
const genderText = (gender) => gender === '1' ? '男' : '女'
const genderColor = (gender) => ({
  color: gender === '1' ? '#409EFF' : '#F56C6C'
})

// 数字格式化过滤器
// const formatNumber = (value) => {
//   if (!value) return '0'
//   if (value >= 10000) return `${(value/10000).toFixed(1)}w`
//   if (value >= 1000) return `${(value/1000).toFixed(1)}k`
//   return value.toString()
// }

// 初始化加载标签
onMounted(() => {
  loadTags()
})

// 选中状态逻辑
const toggleSelection = (escort) => {
  const index = selectedEscorts.value.findIndex(e => e.id === escort.id)
  if (index === -1) {
    selectedEscorts.value.push(escort)
  } else {
    selectedEscorts.value.splice(index, 1)
  }
}

const isSelected = (escort) => {
  return selectedEscorts.value.some(e => e.id === escort.id)
}

// 修改后的价格计算
const calculatedPrice = computed(() => {
  if (!selectedTime.value || !room.value.price) return 0

  // 计算总小时数（分钟转小时，保留2位小数）
  const totalHours = (timeDuration.value / 60).toFixed(2)

  // 计算陪玩总价
  const escortTotal = selectedEscorts.value.reduce((sum, e) => sum + e.price, 0)

  // 总价 = 小时数 × (房间单价 + 陪玩总价)
  return totalHours * (room.value.price + escortTotal)
})

// 修改后的订单提交
const submitOrder = async () => {
  submitting.value = true;
  try {
    const params = {
      userId: user.value.id,
      roomId: room.value.id,
      escortIdList: selectedEscorts.value.map(e => e.id),
      appointmentDate: selectedSlot.value.scheduleDate,
      startTime: dayjs(selectedTime.value[0]).format('HH:mm'),
      endTime: dayjs(selectedTime.value[1]).format('HH:mm')
    };

    const res = await axios.post(BASE_URL+'/v1/schedule/order/create', params);
    if (res.data.code === 2000) {
      await router.push(`/order`);
    }
  } finally {
    submitting.value = false;
  }
};
</script>

<style scoped>
.booking-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

.header-title {
  font-size: 18px;
  font-weight: 500;
}

.schedule-calendar {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 15px;
  margin-top: 20px;
}

.day-card {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 10px;
  background: #fff;
}

.day-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  margin-bottom: 10px;
  background: #f8f9fa;
  border-radius: 4px;

  .date {
    font-weight: bold;
  }

  .day-status {
    font-size: 12px;
    padding: 4px 8px;
    border-radius: 12px;

    &.available {
      background: #e8f4ff;
      color: #409eff;
    }

    &.unavailable {
      background: #fef0f0;
      color: #f56c6c;
    }
  }
}

.time-slots {
  display: grid;
  gap: 8px;
}

.time-slot {
  padding: 8px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;

  &.available {
    border: 1px solid #409eff;
    background: #e8f4ff;

    &:hover {
      background: #d3e8ff;
    }
  }

  &.disabled {
    background: #fef0f0;
    border-color: #f56c6c;
    cursor: not-allowed;
  }

  &.selected {
    background: #409eff;
    color: white;

    .slot-status {
      color: rgba(255, 255, 255, 0.8);
    }
  }
}

.slot-time {
  font-size: 12px;
  font-weight: bold;
}

.slot-status {
  font-size: 12px;
  color: #666;
}

.action-buttons {
  margin-top: 30px;
  text-align: center;
}

.escort-tag {
  margin-right: 8px;
}

.total-price {
  font-size: 18px;
  color: #f56c6c;
  font-weight: bold;
}

.selected-time {
  margin-top: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  text-align: center;
  font-weight: 500;
}


.escort-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
  gap: 20px;
  padding: 20px 0;
}

.escort-card {
  position: relative;
  margin: 10px;
  transition: transform 0.3s;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
  }
}

.card-header {
  display: flex;
  align-items: center;
  padding: 15px;
  gap: 15px;

  .selection-checkbox {
    position: absolute;
    top: 10px;
    right: 10px;
  }

  .base-info {
    flex: 1;

    .username {
      margin: 0 0 8px;
      font-size: 18px;
      color: #303133;
    }

    .meta {
      display: flex;
      align-items: center;
      gap: 15px;

      .gender {
        display: flex;
        align-items: center;
        gap: 5px;
        font-size: 14px;
        color: #606266;

        .el-icon {
          font-size: 18px;
        }
      }

      .rating {
        ::v-deep .el-rate__icon {
          font-size: 18px;
        }
      }
    }
  }
}

.image-carousel {
  border-radius: 8px;
  overflow: hidden;
  margin: 10px 0;

  .carousel-image {
    width: 100%;
    height: 100%;
  }
}

.tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin: 10px 0;
}

.tag-item {
  border-radius: 12px;
  padding: 0 12px;
  transition: all 0.3s;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 2px 6px rgba(0,0,0,0.1);
  }
}

.details {
  margin: 15px;

  ::v-deep .el-descriptions__label {
    width: 80px;
    justify-content: flex-end;
  }

  .price {
    color: #F56C6C;
    font-weight: bold;
  }
}

.signature {
  padding: 0 15px 15px;
  font-style: italic;
  color: #909399;
}

.el-carousel__indicators {
  bottom: 10px;
}

.metrics-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
  gap: 15px;
  padding: 15px;
  background: #f8fafc;
  border-radius: 8px;
  margin: 10px 0;
}

.metric-item {
  display: flex;
  align-items: center;
  padding: 8px;
  transition: all 0.3s;
  border-radius: 6px;

  &:hover {
    background: rgba(64,158,255,0.05);
    transform: translateY(-2px);
  }
}

.metric-icon {
  font-size: 24px;
  margin-right: 12px;
  padding: 8px;
  background: rgba(255,255,255,0.9);
  border-radius: 50%;
  box-shadow: 0 2px 6px rgba(0,0,0,0.05);
}

.metric-content {
  flex: 1;
  .metric-value {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    line-height: 1.2;
  }
  .metric-label {
    font-size: 12px;
    color: #909399;
    margin-top: 2px;
  }
}

.price-item {
  .metric-value {
    color: #F56C6C;
    font-weight: bold;
  }
}

@media (max-width: 768px) {
  .metrics-grid {
    grid-template-columns: repeat(3, 1fr);
  }

  .metric-item {
    flex-direction: column;
    text-align: center;
    .metric-icon {
      margin: 0 0 8px 0;
    }
  }
}

/* 选中状态样式 */
.escort-card {
  position: relative;
  cursor: pointer;
  transition: all 0.3s;
  border: 2px solid transparent;

  &:hover {
    border-color: var(--el-color-primary-light-5);
  }

  &.selected-card {
    border-color: var(--el-color-primary);
    background: rgba(64, 158, 255, 0.05);
  }
}

.selection-indicator {
  position: absolute;
  top: 12px;
  left: 12px;
  width: 24px;
  height: 24px;
  border: 2px solid var(--el-border-color);
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: white;
  z-index: 1;

  .check-icon {
    color: var(--el-color-primary);
    font-size: 18px;
    font-weight: bold;
  }
}

.selected-card .selection-indicator {
  border-color: var(--el-color-primary);
  background: var(--el-color-primary-light-9);
}

/* 调整头部间距 */
.card-header {
  padding: 15px 15px 10px 15px;
}

.order-confirm {
  max-width: 800px;
  margin: 20px auto;
}

.escort-list {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.escort-item {
  display: flex;
  align-items: center;
  padding: 8px;
  background: #f8f9fa;
  border-radius: 20px;
  transition: all 0.3s;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 2px 6px rgba(0,0,0,0.1);
  }

  .escort-name {
    margin-left: 8px;
    font-size: 14px;
  }
}

.total-price {
  font-size: 18px;
  font-weight: bold;
  color: #f56c6c;

  ::v-deep .el-descriptions__content {
    font-size: 18px !important;
  }
}
</style>
